import { ref } from 'vue';
import common from '@/api/common';
import { getStorage, clearStorage } from '@/utils/uni-storage';
import { showSuccessToastWithNavget } from '@/utils/messageTip';

interface changePasswordForm {
    oldPassword: string;
    newPassword: string;
    confirmNewPassword: string;
}

export default function useChangePassword() {
    const formRef = ref();

    const form = ref<changePasswordForm>({
        oldPassword: '',
        newPassword: '',
        confirmNewPassword: '',
    });

    const rules = ref({
        oldPassword: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入原密码',
                },
            ],
        },
        newPassword: {
            rules: [
                {
                    required: true,
                    errorMessage: '请输入新密码',
                },
            ],
        },
        confirmNewPassword: {
            rules: [
                {
                    required: true,
                    errorMessage: '请确认新密码',
                },
                {
                    validateFunction: (rule: any, value: any) => {
                        return form.value.newPassword.trim() === value.trim();
                    },
                    errorMessage: '两次输入密码不一致',
                },
            ],
        },
    });

    async function submit() {
        const validForm = ref<boolean>(false);
        await formRef.value.validate((valid: boolean) => {
            if (!valid) {
                validForm.value = true;
            } else {
                validForm.value = false;
            }
        });

        if (!validForm.value) {
            return;
        }

        uni.showModal({
            content: '是否确认更改密码？',
            success: (res) => {
                if (res.confirm) {
                    submitForm();
                }
            },
        });
    }

    async function submitForm() {
        const data = {
            oldPassword: form.value.oldPassword,
            newPassword: form.value.newPassword,
            userId: getStorage('userInfo').id,
        };

        const res = await common.changePassword(data);

        if (res) {
            clearStorage();
            showSuccessToastWithNavget('/pages/login/index');
        }
    }

    return {
        form,
        formRef,
        rules,
        submit,
        submitForm,
    };
}
